package com.example.chamberlainserver.security;

import com.example.chamberlainserver.Entry.Role;
import com.example.chamberlainserver.Entry.User;
import com.example.chamberlainserver.Service.UserRoleService;
import com.example.chamberlainserver.Service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 实现Spring Security的UserDetailsService接口，用于加载用户特定数据
 */
@Service
public class JwtUserDetailsService implements UserDetailsService {

    @Autowired
    private UserService userService;
    
    @Autowired
    private UserRoleService userRoleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 通过学号查找用户
        User user = userService.getUserByStuNo(username);
        if (user == null) {
            throw new UsernameNotFoundException("未找到用户: " + username);
        }

        // 设置用户权限
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        
        // 从用户角色关联表中获取用户角色
        List<Role> roles = userRoleService.getRolesByUserId(user.getId());
        
        if (roles != null && !roles.isEmpty()) {
            // 如果用户有关联角色，则使用关联角色
            boolean isTeacher = false;
            for (Role role : roles) {
                String roleWithPrefix = RoleConstants.getRoleWithPrefix(role.getRoleCode());
                authorities.add(new SimpleGrantedAuthority(roleWithPrefix));
                
                // 检查是否为TEACHER角色
                if (RoleConstants.ROLE_TEACHER.equals(roleWithPrefix)) {
                    isTeacher = true;
                }
            }
            
            // 如果是TEACHER角色，自动添加ADMIN和MANAGER角色的权限
            if (isTeacher) {
                authorities.add(new SimpleGrantedAuthority(RoleConstants.ROLE_ADMIN));
                authorities.add(new SimpleGrantedAuthority(RoleConstants.ROLE_BUTLER)); // MANAGER对应BUTLER
            }
        } else {
            // 如果用户没有关联角色，默认为部员角色
            authorities.add(new SimpleGrantedAuthority(RoleConstants.getRoleWithPrefix("MEMBER")));
        }

        // 返回UserDetails对象
        return new org.springframework.security.core.userdetails.User(
                user.getStuNo(), user.getPassword(), authorities);
    }
}